<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :search.sync="search"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowFakeDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <!--      <template slot="menuLeft">-->
      <!--        <el-button type="primary"-->
      <!--                   size="small"-->
      <!--                   icon="el-icon-add"-->
      <!--                   plain-->
      <!--                   @click="handleAdd">添加店铺-->
      <!--        </el-button>-->
      <!--      </template>-->
      <!--      <template slot-scope="{tenantId, disabled}" slot="tenantIdForm">-->
      <!--        <el-tag v-if="userInfo.tenantId === '000000'">新增</el-tag>-->
      <!--        <el-tag v-else-if="type=='edit'">修改</el-tag>-->
      <!--        <el-tag v-else-if="type=='view'">查看</el-tag>-->
      <!--        <el-tag>{{ user.name ? user.name : '暂时没有内容' }}</el-tag>-->
      <!--        <el-input :disabled="disabled" v-model="user.name"></el-input>-->
      <!--      </template>-->
      <template slot-scope="scope" slot="menu">
        <el-button
          v-if="scope.row.status === 1 && vaildData(permission.shop_delete, false)"
          type="danger"
          size="small"
          @click.stop="rowFakeDel(scope.row)"
        >删除
        </el-button>
        <el-button
          v-if="scope.row.status === 2 && vaildData(permission.shop_review, false)"
          type="success"
          size="small"
          @click.stop="rowReview(scope.row)"
        >审核
        </el-button>
      </template>
      <template slot="search" slot-scope="{row,size}">
        <div class="el-form-item el-form-item--small avue-form__item--">
          <label class="el-form-item__label">所属客户：</label>
          <el-autocomplete v-model="tenantName" style="width:200px" :fetch-suggestions="queryTenantAsync"
                           placeholder="搜索所属客户" @select="handleTenantSelect" clearable
                           @change="handleTenantChange"></el-autocomplete>
        </div>
        <div class="el-form-item el-form-item--small avue-form__item--">
          <label class="el-form-item__label">开店日期：</label>
          <el-date-picker
            style="margin-right: 10px; width: 450px !important; height: 32px; line-height: 32px;"
            v-model="search.dateRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions">
          </el-date-picker>
        </div>
      </template>
    </avue-crud>
    <el-dialog
      title="店铺删除审核"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <div>
        <h3>店铺删除后相关订单等信息也会一并移除，请谨慎操作！</h3>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false;">关 闭</el-button>
        <el-button type="danger" @click="rowReviewFail">驳 回</el-button>
        <el-button type="primary" @click="rowReviewSuccess">通 过</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, auth} from "@/api/shop/shop";
import {getSelect as tenantSelect} from "@/api/system/tenant";
import {mapGetters} from "vuex";

// const tenantIdDisplay = userInfo().tenantId === '000000'
export default {
  computed: {
    ...mapGetters(["permission", "userInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.shop_add, false) && !window.location.href.includes('www.yongrun.top'),
        viewBtn: false,
        delBtn: false,
        editBtn: this.vaildData(this.permission.shop_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    tenantIdDisplay() {
      return this.userInfo.tenantId === '000000'
    }
  },
  data() {
    return {
      rowSelected: {},
      dialogVisible: false,
      search: {},
      tenantName: '',
      tenantList: [],
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        labelWidth: 200,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        refreshBtn: false,
        searchShowBtn: false,
        selection: true,
        column: [
          {
            label: "店铺名称",
            prop: "resourceOwner",
            rules: [{
              required: true,
              message: "请输入店铺名称",
              trigger: "blur"
            }]
          },
          {
            label: "所属客户",
            prop: "tenantId",
            type: "tree",
            dicUrl: "/api/blade-system/tenant/select",
            props: {
              label: "tenantName",
              value: "tenantId"
            },
            display: false,
            show: false,
            search: true,
            hide: true,
            rules: [{
              required: true,
              message: "请输入所属客户",
              trigger: "click"
            }]
          },
          {
            label: "营业执照",
            prop: "businessLicense",
          },
          {
            label: "执照店铺法人",
            prop: "businessLicenseLegal",
          },
          {
            label: "手机号",
            prop: "telephone",
            overHidden: true
          },
          {
            label: "手机号法人",
            prop: "telephoneLegal",
          },
          {
            label: "支付宝账号",
            prop: "aliPayAccount",
            overHidden: true
          },
          {
            label: "支付宝法人",
            prop: "aliPayLegal",
          },
          {
            label: "支付宝绑定的手机号",
            prop: "aliPayTelephone",
            overHidden: true
          },
          {
            label: "付款诚信通支付宝",
            prop: "cxtAlipay",
          },
          {
            label: "服务器购买账号",
            prop: "serverBuyAccount",
            overHidden: true
          },
          {
            label: "服务器id",
            prop: "serverId",
          },
          {
            label: "服务器购买账号认证人",
            prop: "serverBuyPerson",
          },
          {
            label: "开店日期",
            prop: "openDate",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd 00:00:00",
            rules: [{
              required: true,
              message: "请输入店铺名称",
              trigger: "blur"
            }]
          },
        ]
      },
      data: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setHours(0, 0, 0, 0)
              end.setHours(23, 59, 59, 999)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setHours(0, 0, 0, 0)
              end.setHours(23, 59, 59, 999)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setHours(0, 0, 0, 0)
              end.setHours(23, 59, 59, 999)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setHours(0, 0, 0, 0)
              end.setHours(23, 59, 59, 999)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
              picker.$emit('pick', [start, end]);
            }
          }]
      },
    };
  },
  mounted() {
    this.loadTenantList()
    const code = new URL(window.location.href).searchParams.get('code');
    if (code) {
      auth(code).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        window.location.href = `${window.location.origin}${window.location.hash}`
      }, error => {
        window.console.log(error);
        loading();
      });
    }
  },
  methods: {
    handleClose(){
      this.rowSelected = {}
      this.dialogVisible = false
    },
    handleTenantSelect(val) {
      this.search.tenantId = val.id
    },
    handleTenantChange(val) {
      if (val === '') {
        this.search.tenantId = ''
      }
    },
    queryTenantAsync(queryString, cb) {
      const restaurants = this.tenantList;
      const results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    loadTenantList() {
      tenantSelect().then(res => {
        this.tenantList = res.data.data.map(item => {
          return {value: item.tenantName, id: item.tenantId}
        })
      })
    },
    rowSave(row, done, loading) {
      delete row['payCount']
      delete row['payUserCount']
      delete row['visitUserCount']
      delete row['watchCount']
      if (!row.tenantId || row.tenantId === '') {
        row.tenantId = this.userInfo.tenantId
      }
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      delete row['payCount']
      delete row['payUserCount']
      delete row['visitUserCount']
      delete row['watchCount']
      if (!row.tenantId || row.tenantId === '') {
        row.tenantId = this.userInfo.tenantId
      }
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowFakeDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const params = {
            id: row.id,
            status: 2
          }
          update(params).then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }, error => {
            window.console.log(error);
            loading();
          });
        })
    },
    rowReview(row) {
      this.rowSelected = row
      this.dialogVisible = true
    },
    rowReviewSuccess() {
      this.$confirm("确定通过删除数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.rowSelected.id);
        })
        .then(() => {
          this.handleClose()
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    rowReviewFail() {
      const params = {
        id: this.rowSelected.id,
        status: 1
      }
      update(params).then(() => {
        this.onLoad(this.page);
        this.handleClose()
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    handleAdd() {
      const appid = '5999210'
      // const url = `${window.location.origin}/#/shop/shop`
      const url = `${window.location.origin}/#/authredirect-alibaba`
      window.location.href = `https://auth.1688.com/oauth/authorize?client_id=${appid}&site=1688&redirect_uri=${url}`
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.tenantName = ''
      this.search.tenantId = ''
      this.search.dateRange = ''
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.findObject(this.option.column, "tenantId").search = false;
      if (this.search.dateRange && this.search.dateRange !== '') {
        params.dateStart = this.search.dateRange[0]
        params.dateEnd = this.search.dateRange[1]
      }
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        if (this.data.length !== 0) {
          const isHideInfo = this.data[0].isHideInfo
          if (isHideInfo) {
            this.findObject(this.option.column, "businessLicenseLegal").display = false;
            this.findObject(this.option.column, "businessLicenseLegal").hide = true;
            this.findObject(this.option.column, "telephone").display = false;
            this.findObject(this.option.column, "telephone").hide = true;
            this.findObject(this.option.column, "telephoneLegal").display = false;
            this.findObject(this.option.column, "telephoneLegal").hide = true;
            this.findObject(this.option.column, "aliPayAccount").display = false;
            this.findObject(this.option.column, "aliPayAccount").hide = true;
            this.findObject(this.option.column, "aliPayLegal").display = false;
            this.findObject(this.option.column, "aliPayLegal").hide = true;
            this.findObject(this.option.column, "aliPayTelephone").display = false;
            this.findObject(this.option.column, "aliPayTelephone").hide = true;
            this.findObject(this.option.column, "cxtAlipay").display = false;
            this.findObject(this.option.column, "cxtAlipay").hide = true;
            this.findObject(this.option.column, "serverBuyAccount").display = false;
            this.findObject(this.option.column, "serverBuyAccount").hide = true;
            this.findObject(this.option.column, "serverId").display = false;
            this.findObject(this.option.column, "serverId").hide = true;
            this.findObject(this.option.column, "serverBuyPerson").display = false;
            this.findObject(this.option.column, "serverBuyPerson").hide = true;
            this.findObject(this.option.column, "openDate").display = false;
            this.findObject(this.option.column, "openDate").hide = true;
          }
        }
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style lang="scss">
.avue-crud .el-input__inner, .avue-form .el-input__inner {
  height: 32px;
}
</style>
